str = r"C:\User\Wcy\OneDrive\桌布\workspace\test.txt"
with open(str) as file:
print(file.read())
apple
加入昨天學的異常處理
str = r'C:\User\Wcy\OneDrive\桌布\workspace\test.txttttt'
with open(str) as file:
print(file.read())
except FileNotFoundError:
print("檔案不存在")
檔案不存在
#在open建立Test.txt檔案
str = r'C:\User\Wcy\OneDrive\桌布\workspace\Test.txt'
#並輸入文字進入檔案中
text = "Hi!\nNice to meet you"
#將檔案打開並寫入
with open(str, 'w') as file:
file.write(test)
到桌面可看到檔案及文字
with open(str, 'a') as file:
file.write('\n be happy!')
with open(str, 'w') as file:
file.write('\n be happy!')
需導入shutil模組,今天介紹三種功能
1.copyfile:只複製文件的內容,不複製描述內容ex:什麼時候建立
2.copy:只複製內容不複製原數據(目錄也可以使用)
3.copy2:更強大,可複製文件內容也可複製文件描述資訊ex:權限...
import shuilt
w = r'C:\User\Wcy\OneDrive\桌布\workspace'
source = f"{w}/source_file.txt"
destination = f"{w}/destination_file.txt"
shutil.copyfile(source, destination)#(文件來源,文件目的)
import OS
path = r'C:\User\Wcy\OneDrive\桌布\workspace'
os.remove(f"{path}/test.txt")
import OS
path = r'C:\User\Wcy\OneDrive\桌布\workspace'
os.rmdir(f"{path}/dirc")
import OS
import shutil
path = r'C:\User\Wcy\OneDrive\桌布\workspace'
os.rmdir(f"{path}/dirc")
shutil.rmtree()
import send2trash
path = r'C:\User\Wcy\OneDrive\桌布\workspace'
sand2trash.send2trash(fr"{path}\test.txt")